package com.dxf.securitys.filter;


import com.dxf.common.utils.GlobalConstant;
import com.dxf.common.utils.RedisUtil;
import com.dxf.common.utils.ResponseUtil;
import com.dxf.common.utils.ResultJson;
import com.dxf.securitys.entity.SecurityUser;
import com.dxf.securitys.entity.User;
import com.dxf.securitys.security.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


/**
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 */
@Slf4j
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisUtil redisUtil;

    public TokenLoginFilter(AuthenticationManager authenticationManager
            , TokenManager tokenManager, RedisUtil redisUtil) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisUtil = redisUtil;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/login","POST"));
    }

    /**
     * 1.获取用户名和密码
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
            String username = obtainUsername(req);
            String password = obtainPassword(req);
            log.info("1.获取用户名和密码=="+password);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,password, new ArrayList<>()));

    }

    /**
     *  3.登录成功保存用户达到redis并返回token
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        String token = tokenManager.createToken(user.getCurrentUserInfo().getAccount());

        redisUtil.set(user.getCurrentUserInfo().getAccount(),user, GlobalConstant.REDIS_SAVE_TIME);
        log.info(" 3.登录成功保存用户达到redis并返回token=="+token);
        ResponseUtil.out(res, ResultJson.ok().data(GlobalConstant.ACCESS_TOKEN, token));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, ResultJson.error().message("账号或密码错误"));
    }
}
